package com.cd2cd.code_template.configuration;

import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.hibernate.validator.resourceloading.PlatformResourceBundleLocator;
import org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

@Configuration
public class ValidatorConfiguration {

    /**
     * controller 方法上的验证返回 <br/>
     * 使用方法： https://blog.csdn.net/wang___wang___/article/details/88413416
     * @return
     */
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
        /**设置validator模式为快速失败返回*/
        postProcessor.setValidator(validator());
        return postProcessor;
    }

    @Bean
    public Validator validator(){
        ValidatorFactory validatorFactory = Validation.byDefaultProvider()
                .configure()
                .addProperty( "hibernate.validator.fail_fast", "false" )
                .messageInterpolator(
                        new ResourceBundleMessageInterpolator(
                                new PlatformResourceBundleLocator( "javax.validation.constraints.i18n.ValidationMessages" )
                        )
                )
                .buildValidatorFactory();

        // ValidationMessages.properties
        // _zh_CN _en

        return validatorFactory.getValidator();
    }

}
